<template>
  <div class="app-container">
    <el-card>
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <!-- 基础信息 start -->
        <div class="base">
          <TitleLine title="基础信息" />
          <!-- 关联会员 start -->
          <el-form-item label="关联会员">
            <div>
              <div class="flex align-end" v-if="relevancyUser.mobile">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="relevancyUser.profilePhoto"
                ></el-image>
                <div class="ml-10">
                  <p>{{ relevancyUser.nickName }}</p>
                  <p>{{ relevancyUser.mobile }}</p>
                </div>
                <el-link
                  class="ml-10"
                  :underline="false"
                  type="primary"
                  @click="checkDailogShow = true"
                  >重新选择</el-link
                >
              </div>
              <div v-else class="check-user-btn" @click="checkDailogShow = true">+</div>
              <p>从会员列表进行选择</p>
            </div>
          </el-form-item>
          <el-form-item label="企业名称" prop="enterpriseName">
            <el-input
              v-model="formData.enterpriseName"
              placeholder="请输入企业名称"
              :maxlength="30"
              :minlength="2"
              clearable
              :style="{ width: '50%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="营业执照号" prop="licenseNo">
            <el-input
              v-model="formData.licenseNo"
              placeholder="请输入营业执照号"
              :maxlength="20"
              :minlength="13"
              clearable
              :style="{ width: '50%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="主营业务" prop="businessScope">
            <el-input
              v-model="formData.businessScope"
              placeholder="请输入主营业务"
              :maxlength="30"
              clearable
              :style="{ width: '50%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="touchName">
            <el-input
              v-model="formData.touchName"
              placeholder="请输入联系人"
              :maxlength="15"
              clearable
              :style="{ width: '30%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="touchMobile">
            <el-input
              v-model="formData.touchMobile"
              placeholder="请输入联系电话"
              :maxlength="12"
              clearable
              :style="{ width: '30%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="联系地址">
            <AreaMultipleSelect ref="areaMultipleSelect" type="update" v-model="formData.address" />
          </el-form-item>
          <el-form-item>
            <el-input
              type="textarea"
              :rows="4"
              v-model.trim="formData.detailAddress"
              maxlength="50"
              show-word-limit
              placeholder="请输入详细地址"
              clearable
              :style="{ width: '40%' }"
            >
            </el-input>
          </el-form-item>
        </div>
        <!-- 基础信息 end -->

        <!-- 营业执照 start -->
        <el-form-item class="business">
          <TitleLine style="margin-left: -100px" title="营业执照" />
          <UploadImage
            :isShowTip="true"
            :file-type="['jpg', 'png', 'jpeg']"
            file-pixel="60*60"
            :file-size="1"
            :limit="1"
            v-model="formData.licenseImg"
          />
        </el-form-item>
        <!-- 营业执照 end -->

        <!-- 账号状态 start -->
        <el-form-item class="status" label="账号状态">
          <el-radio-group v-model="formData.verifyStatus">
            <el-radio :label="3">开通</el-radio>
            <el-radio :label="4">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 账号状态 end -->

        <!-- 冻结理由 -->
        <el-form-item label="冻结理由" prop="reason" v-if="formData.verifyStatus === 4">
          <el-input
            type="textarea"
            :rows="4"
            v-model.trim="formData.reason"
            :maxlength="50"
            show-word-limit
            placeholder="请输入冻结理由（1-50个字）"
            clearable
            :style="{ width: '40%' }"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <div class="flex justify-center mt-20">
      <el-button @click="cancle">取消</el-button>
      <el-button type="primary" @click="doSave">保存</el-button>
    </div>

    <!-- 选择关联客户弹窗 -->
    <CompanyEditCheck v-model="checkDailogShow" @confirmCheckUser="getCheckUser" />
  </div>
</template>

<script>
import CompanyEditCheck from './components/CompanyEditCheck.vue'
import _ from 'lodash'
export default {
  name: 'CompanyEdit',
  components: {
    // 选择关联客户
    CompanyEditCheck
  },
  props: {},
  data() {
    // 联系电话自定义验证
    const touchMobilePass = (rule, value, callback) => {
      const regOne = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      const regTwo = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
      if (!regOne.test(value) && !regTwo.test(value)) {
        callback(new Error('请输入正确的联系电话!'))
      } else {
        callback()
      }
    }
    return {
      // 选择关联客户弹窗是否显示
      checkDailogShow: false,
      // 选择的关联用户
      relevancyUser: {
        // 头像
        profilePhoto: '',
        // 手机号
        mobile: '',
        // 昵称
        nickName: ''
      },
      // 表单内容
      formData: {
        // 用户ID
        userId: '',
        // 企业名称
        enterpriseName: '',
        // 营业执照号
        licenseNo: '',
        // 	业务范围
        businessScope: '',
        // 联系人
        touchName: '',
        // 联系电话
        touchMobile: '',
        // 地址对象
        address: {
          provinceObj: {
            name: '',
            id: ''
          },
          cityObj: {
            name: '',
            id: ''
          },
          countyObj: {
            name: '',
            id: ''
          }
        },
        // 详细地址
        detailAddress: '',
        // 营业执照
        licenseImg: [],
        // 账号状态
        verifyStatus: 4,
        // 审核理由
        reason: ''
      },
      rules: {
        enterpriseName: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          },
          { min: 2, max: 30, message: '请输入企业名称长度在2到30个字符', trigger: 'blur' }
        ],
        licenseNo: [
          {
            required: true,
            message: '请输入营业执照号',
            trigger: 'blur'
          },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: '请输入数字或英文字符',
            trigger: ['blur', 'change']
          },
          { min: 13, max: 20, message: '营业执照号长度在13到20个字符', trigger: 'blur' }
        ],
        businessScope: [
          {
            required: true,
            message: '请输入主营业务',
            trigger: 'blur'
          }
        ],
        touchName: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }
        ],
        touchMobile: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          },
          {
            validator: touchMobilePass,
            trigger: 'blur'
          },
          { min: 9, max: 12, message: '联系电话长度在13到20个字符', trigger: 'blur' }
        ],
        reason: [
          {
            required: true,
            message: '请输入冻结理由',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 获取企业主信息
    this.getCompanyInfo()
  },
  mounted() {},
  methods: {
    /**
     * 选择设置管理用户
     * @params {Object} userInfo 关联用户信息
     */
    getCheckUser(userInfo) {
      this.relevancyUser = userInfo
      this.formData.userId = userInfo.id
    },

    // 获取企业主信息
    async getCompanyInfo() {
      const id = this.$route.query.id
      if (!id) return
      try {
        const { data } = await this.$http.user.company.getInfo(id)
        console.log(data)
        // 数据处理
        for (let key in this.relevancyUser) {
          this.relevancyUser[key] = data[key]
        }
        // 地址信息
        this.formData.address.provinceObj = {
          name: data.provinceName,
          id: data?.provinceId ?? ''
        }
        this.formData.address.cityObj = {
          name: data.cityName,
          id: data?.cityId ?? ''
        }
        this.formData.address.countyObj = {
          name: data.districtName,
          id: data?.districtId ?? ''
        }
        // 地址组件回显
        this.$refs.areaMultipleSelect.showBackData({
          provinceObj: this.formData.address.provinceObj,
          cityObj: this.formData.address.cityObj
        })
        // 其余表单数据
        for (let key in this.formData) {
          if (key === 'licenseImg') {
            this.formData[key] = JSON.parse(data[key])[0]
          } else if (key !== 'address') {
            this.formData[key] = data[key]
          }
        }
      } catch (error) {
        console.log('getCompanyInfo', error)
      }
    },

    // 点击取消
    cancle() {
      this.$router.back()
    },

    // 点击保存
    doSave: _.debounce(function () {
      if (!this.formData.userId) {
        this.$message.error('请选择关联会员！')
        return
      }

      this.$refs.elForm.validate(valid => {
        if (!valid) return
        // 参数整理
        const params = this.$lodash.cloneDeep(this.formData)
        params.provinceName = params.address.provinceObj.name
        params.provinceId = params.address.provinceObj.id
        params.cityName = params.address.cityObj.name
        params.cityId = params.address.cityObj.id
        params.districtName = params.address.countyObj.name
        params.districtId = params.address.countyObj.id
        params.licenseImg = [params.licenseImg]
        // 发送相应请求
        if (!this.$route.query.id) {
          // 新增
          this.addCompany(params)
        } else {
          // 修改
          this.editCompany(params)
        }
      })
    }, 400),

    // 新增企业主
    async addCompany(params) {
      try {
        const res = await this.$http.user.company.addInfo(params)
        // console.log(res)
        if (res.status === 200) {
          this.$message.success('添加成功')
          this.$router.back()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.log('addCompany', error)
      }
    },

    // 编辑企业主
    async editCompany(params) {
      params = { ...params, id: this.$route.query.id }
      try {
        const res = await this.$http.user.company.editInfo(params)
        if (res.status === 200) {
          this.$message.success('修改成功')
          this.$router.back()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.log('editCompany', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.check-user-btn {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
